package com.yedean.factory.support;

import com.yedean.factory.BeansException;
import com.yedean.factory.ConfigurableListableBeanFactory;
import com.yedean.factory.config.BeanDefinition;

import java.util.HashMap;
import java.util.Map;

/**
 * DafaultListableBeanFactory 默认可列出beanDefiniton的bean工厂
 * 1.提供bean定义的集合
 *
 * @author yedean
 * @date 2022/6/28
 */
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements BeanDefinitionRegistry, ConfigurableListableBeanFactory {

    private final Map<String, BeanDefinition> beanDefinitionMap = new HashMap<>();


    @Override
    public BeanDefinition getBeanDefinition(String name) {
        return beanDefinitionMap.get(name);
    }

    @Override
    public void preInstantiateSingletons() throws BeansException {
        beanDefinitionMap.keySet().forEach(this::getBean);
    }

    @Override
    public String[] getBeanDefinitionNames() {
        return beanDefinitionMap.keySet().toArray(new String[0]);
    }

    @Override
    public <T> Map<String, T> getBeansOfType(Class<T> tClass) {
        Map<String,T> result =new HashMap<>();
        beanDefinitionMap.forEach((x,y)->{
            Class<?> beanClass = y.getBeanClass();
            if (tClass.isAssignableFrom(beanClass)){
                result.put(x, (T) getBean(x));
            }
        });
        return result;
    }

    @Override
    public void registerBeanDefinition(String name, BeanDefinition beanDefinition) {
        beanDefinitionMap.put(name, beanDefinition);
    }

    @Override
    public boolean containsBeanDefinition(String beanName) {
        return beanDefinitionMap.containsKey(beanName);
    }
}
